package com.azt.back.action.gift;

import java.io.IOException;
import java.security.Timestamp;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.azt.api.pojo.Delivery;
import com.azt.api.pojo.GiftExchange;
import com.azt.api.pojo.GiftInfo;
import com.azt.api.pojo.GiftStock;
import com.azt.api.service.DeliveryService;
import com.azt.api.service.GiftService;
import com.azt.back.util.ContextUtils;
import com.azt.back.util.Globals;
import com.azt.model.AjaxJson;
import com.azt.model.page.Pagination;
import com.azt.utils.CommonUtil;
import com.azt.utils.RequestUtils;

@Controller
@RequestMapping("/gift")
public class GiftAction {
	
		@Autowired
		private GiftService giftService;
		
		@Autowired
		private DeliveryService deliveryService;
		
		@RequestMapping("/gift_list.do")
	    public String selectMemberList(Model model, HttpServletRequest request, Integer pageNo) {
	        Map<String, String> searchMap = RequestUtils.getSearchMap(request);
	        Pagination pagination = giftService.giftInfoList(pageNo == null ? 1 : pageNo, 10, searchMap);
	        model.addAttribute("pagination", pagination);
	        RequestUtils.MapToModelMap(searchMap, request);
	        return "gift/gift_list";
	    }
		
		@RequestMapping("/gift_exchange_list.do")
		public String selectGiftExchangeList(Model model, HttpServletRequest request, Integer pageNo){
			 Map<String, String> searchMap = RequestUtils.getSearchMap(request);
		     Pagination pagination = giftService.giftExchangePage(pageNo == null ? 1 : pageNo, 10, searchMap);
		     List<Delivery> deliveryList=deliveryService.findAllDelivery();
		     model.addAttribute("deliverys", deliveryList);
		     model.addAttribute("pagination", pagination);
		     RequestUtils.MapToModelMap(searchMap, request);
		     return "gift/gift_exchange_list";
		}
		
		@RequestMapping("/giftInfo_add.do")
		public String toAddGiftInfo(Model model,GiftInfo g){
			model.addAttribute("gift", g);
			return "gift/gift_form";
		}
		
		@RequestMapping("/giftInfo_edit.do")
		public String toGiftEdit(Model model,Integer id){
			GiftInfo g=giftService.getGiftInfoById(id);
			//String[] arr=g.getImgUrlArr();
			model.addAttribute("gift", g);
			return "gift/gift_form";
		}
		
		@RequestMapping("/subGift.do")
		@ResponseBody
		public AjaxJson subGift(@RequestBody GiftInfo giftInfo){
			AjaxJson aj=new AjaxJson();
			try {
				if(giftInfo.getId()==null){
					giftInfo.setGiftCode(giftService.getGiftCode());
					giftInfo.setState(1);
					giftInfo.setOperateid(ContextUtils.getAdmin().getId());
					giftService.addGiftInfo(giftInfo);
				}else{
					giftService.updateGiftInfo(giftInfo);
				}
			} catch (Exception e) {
				aj=AjaxJson.error("系统异常");
				e.printStackTrace();
			}
			return aj;
		}
		
		@RequestMapping("/plchange.do")
		@ResponseBody
		public AjaxJson plchange(String ids){
			AjaxJson aj=new AjaxJson();
			try {
				if(StringUtils.isNotBlank(ids)){
					giftService.plChangeGiftState(ids);
				}else{
					return AjaxJson.error("没有id");
				}
			} catch (Exception e) {
				aj=AjaxJson.error("系统失败");
				e.printStackTrace();
			}
			return aj;
		}
		
		@RequestMapping("/pldelete.do")
		@ResponseBody
		public AjaxJson pldelete(String ids){
			AjaxJson aj=new AjaxJson();
			try {
				if(StringUtils.isNotBlank(ids)){
					giftService.plDeletegiftInfos(ids);
				}else{
					return AjaxJson.error("没有id");
				}
			} catch (Exception e) {
				aj=AjaxJson.error("系统失败");
				e.printStackTrace();
			}
			return aj;
		}
		
		@RequestMapping("/updateOne.do")
		@ResponseBody
		public AjaxJson updateOne(String id){
			AjaxJson aj=new AjaxJson();
			try {
				giftService.updateGiftStateOne(id);
				aj= AjaxJson.success();
			} catch (Exception e) {
				aj=AjaxJson.error("系统错误");
				e.printStackTrace();
			}
			return aj;
		}
		
		@RequestMapping("/giftStockList.do")
		@ResponseBody
		public AjaxJson giftStockList(Integer id){
			AjaxJson aj=new AjaxJson();
			try {
				List<GiftStock> stockList=giftService.getGiftListByGid(id);
				aj.setObj(stockList);
			} catch (Exception e) {
				aj=AjaxJson.error("系统错误");
				e.printStackTrace();
			}
			return aj;
		}
		
		@RequestMapping("/addGiftStock.do")
		@ResponseBody
		public AjaxJson addGiftStock(GiftStock giftStock){
			AjaxJson aj=new AjaxJson();
			try {
				giftStock.setType(1);
				giftStock.setOperateid(ContextUtils.getAdmin().getId());
				giftService.addGiftStock(giftStock);
			} catch (Exception e) {
				aj=AjaxJson.error("系统错误");
				e.printStackTrace();
			}
			return aj;
		}
		
		@RequestMapping("/setExchange")
		@ResponseBody
		public AjaxJson setExchange(GiftExchange exchange){
			AjaxJson aj=new AjaxJson();
			try {
				exchange.setState(1);
				giftService.updateExchange(exchange);
			} catch (Exception e) {
				aj=AjaxJson.error("系统繁忙");
				e.printStackTrace();
			}
			return aj;
		}
		
		@RequestMapping("/plexport.do")
		public void plexport(HttpServletRequest request,HttpServletResponse response,String state){
			 List<GiftExchange> giftExchanges=giftService.getExportChange(state);
			 try {
				 	String title="未处理清单";
			        HSSFWorkbook wb = new HSSFWorkbook();  
			        HSSFSheet sheet = wb.createSheet(title);  
			        sheet.autoSizeColumn(1);
			        HSSFRow row = sheet.createRow(0);
			        HSSFCellStyle style = wb.createCellStyle();  
			        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			        HSSFCell cell = row.createCell(0);
			        String[] titles={"兑换账号（邮箱）","兑换账号（电话）","兑换礼品","兑换时间",
			        		"联系人","联系电话","邮寄地址","兑换状态"};
			        for (int i = 0; i < titles.length; i++) {
						cell.setCellValue(titles[i]);
						cell.setCellStyle(style);
						cell=row.createCell(i+1);
					}
				 int index = 1;
				 for(GiftExchange gift : giftExchanges) {
					 HSSFRow row1 = sheet.createRow(index);
					 HSSFCell numberCell = row1.createCell(0);
					 HSSFCell telCell = row1.createCell(1);
					 HSSFCell giftNameCell = row1.createCell(2);
					 HSSFCell timeCell = row1.createCell(3);
					 HSSFCell contactNameCell = row1.createCell(4);
					 HSSFCell contactTelCell = row1.createCell(5);
					 HSSFCell addCell =row1.createCell(6);
					 HSSFCell stateCell =row1.createCell(7);
					 numberCell.setCellValue(gift.getEmail());
					 //PrizeSet prize = record.getPrizeSet();
					 //giftnameCell.setCellValue(prize != null ? prize.getGiftName() : "");
					 //createtimeCell.setCellValue(CommonUtil.formatDate(record.getCreatetime(), "yyyy-MM-dd HH:mm"));
					 telCell.setCellValue(gift.getMobile());
					 giftNameCell.setCellValue(gift.getGiftName());
					 timeCell.setCellValue(CommonUtil.formatDate(gift.getCreatetime(),"yyyy-MM-dd HH:mm"));
					 contactNameCell.setCellValue(gift.getContactName());
					 contactTelCell.setCellValue(gift.getContactTel());
					 addCell.setCellValue(gift.getContactAdd());
					 stateCell.setCellValue(gift.getState());
					 Integer stateName=gift.getState();
					 if(stateName==0){
						 stateCell.setCellValue("未寄出");
					 }
					 if(stateName==3){
						 stateCell.setCellValue("未充值");
					 }
					 index ++;
				 }
			      
			        title = title +".xls";
			        title = new String(title.getBytes("UTF-8"), "iso8859-1");
			        
			        response.setContentType("application/vnd.ms-excel;");
			        response.setHeader("Content-Disposition", "attachment;filename="+title);
			        
					ServletOutputStream outputStream = response.getOutputStream();
					wb.write(outputStream);
					outputStream.flush();  
					outputStream.close();  
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
}
